<template>
    <div class="index-lists">
        <el-card class="!border-none" shadow="never">
            <el-form ref="formRef" class="mb-[-16px]" :model="queryParams" :inline="true">
                <el-form-item label="应用渠道">
                    <el-select
                        v-model="queryParams.channel"
                        class="w-[280px]"
                        clearable
                    >
                        <el-option label="全部" value="-1" />
                        <el-option
                            v-for="item in channelType.dictData.channel"
                            :key="item.value"
                            :label="item.name"
                            :value="item.value"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="应用标识" prop="package_name">
                    <el-input class="w-[280px]" v-model="queryParams.package_name" />
                </el-form-item>
                <el-form-item label="账号编号" prop="account_id">
                    <el-input class="w-[280px]" v-model="queryParams.account_id" />
                </el-form-item>
                <el-form-item label="广告主账号" prop="account_number">
                    <el-input class="w-[280px]" v-model="queryParams.account_number" />
                </el-form-item>
                <el-form-item label="广告主名称" prop="account_title">
                    <el-input class="w-[280px]" v-model="queryParams.account_title" />
                </el-form-item>
                <el-form-item label="账号状态" prop="status">
                    <el-select
                        v-model="queryParams.status"
                        class="w-[280px]"
                        clearable
                    >
                        <el-option label="全部" value="-1" />
                        <el-option label="正常" value="1" />
                        <el-option label="无效" value="0" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleSearch">查询</el-button>
                    <el-button @click="handleReset">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>

        <el-card class="!border-none mt-4" shadow="never">
            <el-row :gutter="16">
                <el-col :xs="24" :sm="12" :md="5" class="text-center mb-4">
                    <el-statistic value-style="color:#F56C6C;font-size:16px" title="ROI" :value="divideAndFormat(statisticData.recharge, statisticData.cost)" />
                </el-col>
                <el-col :xs="24" :sm="12" :md="5" class="text-center mb-4">
                    <el-statistic value-style="color:#409EFF;font-size:16px" title="成本" :value="statisticData.cost || 0" />
                </el-col>
                <el-col :xs="24" :sm="12" :md="5" class="text-center mb-4">
                    <el-statistic value-style="color:red;font-size:16px" title="充值" :value="statisticData.recharge || 0"/>
                </el-col>
                <el-col :xs="24" :sm="12" :md="5" class="text-center mb-4">
                    <el-statistic value-style="color:#606266;font-size:16px" title="粉丝数" :value="statisticData.users || 0"/>
                </el-col>
                <el-col :xs="24" :sm="12" :md="4" class="text-center mb-4">
                    <el-statistic value-style="color:#E6A23C;font-size:16px" title="粉价" :value="divideAndFormat(statisticData.cost, statisticData.users)"/>
                </el-col>
            </el-row>
        </el-card>


        <el-card class="!border-none mt-4" shadow="never">
            <div>
                <el-button v-perms="['client:account:add']" type="primary" @click="handleAdd()">
                    <template #icon>
                        <icon name="el-icon-Plus" />
                    </template>
                    新增
                </el-button>
            </div>
            <el-table
                class="mt-4"
                size="large"
                v-loading="pager.loading"
                :data="pager.lists"
            >
                <el-table-column label="账号编号" prop="account_id" min-width="130"/>
                <el-table-column label="应用渠道" prop="channel" min-width="80">
                    <template #default="{ row }">
                        {{ getChannelName(row.channel) }}
                    </template>
                </el-table-column>
                <el-table-column label="广告主账号" show-overflow-tooltip prop="account_number" min-width="100" />
                <el-table-column label="账号名称" show-overflow-tooltip prop="account_title" min-width="100" />
<!--                <el-table-column label="应用标识" show-overflow-tooltip prop="package_name" min-width="100" />-->
                <el-table-column label="ROI" min-width="100">
                    <template #default="{ row }">
                        <el-statistic value-style="color:#F56C6C;font-size:16px" :value="divideAndFormat(row.recharge ,row.cost)"/>
                    </template>
                </el-table-column>
                <el-table-column label="成本"  prop="cost" min-width="100">
                    <template #default="{ row }">
                        <el-statistic value-style="color:#409EFF;font-size:16px" :value="row.cost" />
                    </template>
                </el-table-column>
                <el-table-column label="充值"  prop="recharge" min-width="100">
                    <template #default="{ row }">
                        <el-statistic value-style="color:red;font-size:16px" :value="row.recharge" />
                    </template>
                </el-table-column>
                <el-table-column label="粉丝数"  prop="recharge" min-width="100">
                    <template #default="{ row }">
                        <el-statistic value-style="color:#606266;font-size:16px"  :value="row.users" />
                    </template>
                </el-table-column>
                <el-table-column label="粉价"  prop="recharge" min-width="100">
                    <template #default="{ row }">
                        <el-statistic value-style="color:#E6A23C;font-size:16px"  :value="divideAndFormat(row.cost ,row.users)" />
                    </template>
                </el-table-column>
                <el-table-column label="账号状态" prop="status" min-width="100" >
                    <template #default="{ row }">
                        <el-tag effect="dark" :type="row.status === 1 ? 'success' : 'danger'">
                            {{ row.status === 1 ? '正常' : '无效' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="创建时间" show-overflow-tooltip prop="create_time" min-width="100" />
                <el-table-column label="更新时间" show-overflow-tooltip prop="update_time" min-width="100" />
                <el-table-column label="操作" width="145" fixed="right">
                    <template #default="{ row }">
                        <el-row :gutter="24">
                            <el-button
                                v-perms="['client:account:edit']"
                                @click="handleEdit(row)"
                                link
                            >
                                编辑
                            </el-button>
                            <el-button
                                v-perms="['client:account:del']"
                                type="primary"
                                link
                                @click="handleDelete(row.account_id)"
                            >
                                删除
                            </el-button>
                        </el-row>
                        <el-row :gutter="24">
                            <el-button v-perms="['client:account:bearer_token']" type="success" link>
                                <el-link :href="row.bearer_token_url" target="_blank">去授权</el-link>
                            </el-button>
                            <el-button v-perms="['client:source:list']" type="info" link>
                                <router-link :to="{
                                        path: getRoutePath('client:source:list'),
                                        query: {
                                            account_id: row.account_id,
                                            account_title: row.account_title,
                                        }
                                    }">
                                    外推管理
                                </router-link>
                            </el-button>
                        </el-row>
                        <el-row :gutter="24">
                            <el-button v-perms="['client:client_user:list']" type="warning" link>
                                <router-link :to="{
                                        path: getRoutePath('client:client_user:list'),
                                        query: {
                                            account_id: row.account_id,
                                        }
                                    }">
                                    用户管理
                                </router-link>
                            </el-button>
                            <el-button v-perms="['client:orders:list']" type="danger" link>
                                <router-link :to="{
                                        path: getRoutePath('client:orders:list'),
                                        query: {
                                              account_id: row.account_id,
                                        }
                                    }">
                                    订单管理
                                </router-link>
                            </el-button>
                        </el-row>
                        <el-row :gutter="24">
                            <el-button v-perms="['client:orders:list']" type="primary" link>
                                <router-link :to="{
                                            path: getRoutePath('client:recharge_report:list'),
                                            query: {
                                                  account_id: row.account_id,
                                            }
                                        }">
                                    每日报表
                                </router-link>
                            </el-button>
                        </el-row>

                    </template>
                </el-table-column>
            </el-table>
            <div class="flex justify-end mt-4">
                <pagination v-model="pager" @change="getLists" />
            </div>
        </el-card>
        <edit-popup
            v-if="showEdit"
            ref="editRef"
            @success="getLists"
            @close="showEdit = false"
        />
    </div>
</template>
<script lang="ts" setup name="account">
import { accountDelete, accountLists, accountStatistic } from '@/api/client/account'
import { usePaging } from '@/hooks/usePaging'
import { onMounted, ref } from 'vue'
import feedback from '@/utils/feedback'
import EditPopup from './edit.vue'
import { useDictData } from '@/hooks/useDictOptions'
import { getRoutePath } from '@/router'
const editRef = shallowRef<InstanceType<typeof EditPopup>>()
const showEdit = ref(false)
const queryParams = reactive({
    channel: '-1',
    account_id: '',
    account_number: '',
    account_title: '',
    status: '1',
    package_name: ''
})

const { pager, getLists, resetPage, resetParams } = usePaging({
    fetchFun: accountLists,
    params: queryParams
})


// 手动管理统计数据
const statisticData = ref({
    cost: 0,
    recharge: 0,
    users: 0
})

// 获取统计数据
const fetchStatistic = async () => {
    try {
        const response = await accountStatistic(queryParams)
        statisticData.value = response || { cost: 0, recharge: 0, users: 0 }
    } catch (error) {
        console.error('获取统计数据失败:', error)
        statisticData.value = { cost: 0, recharge: 0, users: 0 }
    }
}

interface DictItem {
    value: string | number
    name: string
}

interface ChannelDictData {
    channel: DictItem[]
}

const channelType = useDictData<ChannelDictData>(['channel'])

const handleAdd = async () => {
    showEdit.value = true
    await nextTick()
    editRef.value?.open('add')
}

const handleEdit = async (data: any) => {
    showEdit.value = true
    await nextTick()
    editRef.value?.open('edit')
    editRef.value?.getDetail(data)
}

const handleDelete = async (account_id: number) => {
    await feedback.confirm('确定要删除？')
    await accountDelete({ account_id })
    feedback.msgSuccess('删除成功')
    getLists()
}

const getChannelName = (channelValue: string | number): string => {
    // 处理字典数据未加载完成的情况
    if (!channelType.dictData.channel) {
        return String(channelValue)
    }

    // 查找匹配的渠道名称
    const channel = channelType.dictData.channel.find(item =>
        String(item.value) === String(channelValue)
    )

    // 返回渠道名称或原始值
    return channel ? channel.name : String(channelValue)
}

function divideAndFormat(dividend: any, divisor: any): string {
    // 转换为数字类型
    const numDividend = Number(dividend);
    const numDivisor = Number(divisor);

    // 检查除数是否为有效数字且不为0
    if (!numDivisor || isNaN(numDivisor) || numDivisor === 0) {
        return '0.00';
    }

    // 检查被除数是否为有效数字
    if (isNaN(numDividend)) {
        return '0.00';
    }

    // 执行除法并保留两位小数
    const result = numDividend / numDivisor;
    return result.toFixed(2);
}


const router = useRouter()
const handleAccountClick = (accountId: string) => {
    router.push({
        path: getRoutePath('client:recharge_report:list'),
        query: {
            account_id: accountId
        }
    })
}


// 统一的查询函数
const handleQuery = async () => {
    await Promise.all([
        getLists(),
        fetchStatistic()
    ])
}

// 重置函数
const handleReset = () => {
    resetParams()
    handleQuery()
}

// 更新模板中的按钮事件
const handleSearch = () => {
    resetPage()
    handleQuery()
}

onMounted(() => {
    handleQuery()
})
</script>
